package com.study.springsecurity.filter;

import com.study.springsecurity.constant.ErrorCode;
import com.study.springsecurity.pojo.Result;
import com.study.springsecurity.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.study.springsecurity.constant.CommonConstant.PageUrl;

/**
 * 登录验证码拦截器
 * OncePerRequestFilter说明：https://www.cnblogs.com/my-king/p/17730301.html
 *
 * @Author YL
 * @Create 2024/3/30 16:17
 * @Version 1.0
 */
@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 只拦截登录接口
        AntPathRequestMatcher post = new AntPathRequestMatcher(PageUrl.LOGIN_URL, "POST");
        if (!post.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 比较验证码
        String inputVerificationCode = request.getParameter("verificationCode");
        log.info("验证码拦截器打印验证码：" + inputVerificationCode);
        HttpSession session = request.getSession();
        String cacheVerificationCode = (String)session.getAttribute("cacheVerificationCode");
        if(StringUtils.isNotBlank(cacheVerificationCode)
                && (StringUtils.equals(inputVerificationCode,"1234") // TODO 跳过验证码
                || StringUtils.equals(inputVerificationCode,cacheVerificationCode))){
            filterChain.doFilter(request, response);
            return;
        }

        // 验证码不一致
        Result result = new Result();
        result.setCode(ErrorCode.E000004.code()).setMessage(ErrorCode.E000004.msg());
        ResponseUtil.writeJsonUtf8(response, HttpStatus.OK, result);
    }
}
